package com.jushu.storbox.actions;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.jushu.storbox.LoginActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.util.CloudDriveDialogUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PollingAlarmUtils;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

public class AuthorizationAction extends Actions {

	public static final String TAG = AuthorizationAction.class.getSimpleName();
	
	public AuthorizationAction(Context context) {
		super(context);
	}
    
    public void handleException(Handler handler, ClientException e, int messageCode, Object obj)
    {
        try
        {
            Message msg = new Message();
            if (null != e)
            {
                LogUtil.e(TAG, "[Exception] webservice messageCode:" + messageCode
                    + " | eStatusCode:" + e.getStatusCode() + " | eCode:" + e.getCode() + " | eMsg:"
                    + e.getMessage());
                msg.what = e.getStatusCode();
                String code = "";
                if (null != e.getCode())
                {
                    code = e.getCode();
                }
                msg.obj = code;
            }
            else
            {
                msg.arg1 = messageCode;
                msg.what = ExceptionConstant.access_internet_Failed;
            }
            handler.sendMessage(msg);
        }
        catch (Exception e2)
        {
            e.printStackTrace();
        }
    }
    

	public void checkLoginState(
			ICloudDriveService service, Handler ahandler, Handler ehandler,
			int messageCode) {
		LogUtil.i(TAG, "checkLoginState[Actions]");
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), ahandler);
				} catch (ClientException e1) {
					handleException(ehandler, e1,
							ClientConfig.SENDFROMLOGIN, null);// 1001
					return;
				}
			}
			
			if (0 != messageCode) {
				LogUtil.i(TAG, "checkLoginState success[Actions]");
		        Message msg = ahandler.obtainMessage(messageCode);
		        msg.sendToTarget();
			}
		}
	}
	
	public boolean checkIsRootAndNotify(final Context context, final Handler handler) {
		if (PublicTools.mdmRootCheck()) {
			try {
				
				final Runnable handleOnExit = new Runnable() {
					public void run() {
						PublicTools.clearData(context);
						Toast.makeText(context,R.string.setting_clear_ok,Toast.LENGTH_LONG).show();
						SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings,Context.MODE_APPEND);
						Editor editor = settings.edit();
						editor.putBoolean(ClientConfig.AUTOLOGIN,false);
						editor.putString(ClientConfig.USERNAME,"");
						editor.putString(ClientConfig.CURRENTUSERNAME,"");
						editor.putString(ClientConfig.LOGINPASSWORD,"");
						editor.commit();

						ShareDriveApplication.getInstance().setAuthorization(null);
						ShareDriveApplication.getInstance().setWnerID(null);
						PublicTools.setExpiredAt(context, 0);

						PollingAlarmUtils.stopPollingService(context,1,"relogin");
						Intent intent = new Intent();
						intent.setClass(context,LoginActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						ActivityTaskManager.getInstance().closeAllActivity();
						context.startActivity(intent);
					}
				};
				
				final Runnable handleExit = new Runnable() {
					public void run() {
						String res = "";
						try {
							res = ServiceFactory.getRemoteFileService().logout();
							LogUtil.e(TAG, "loginout_res:"+ res);
						} catch (ClientException e) {
							LogUtil.e(TAG,"statueCode:"+ e.getStatusCode());
						}
						Message.obtain(handler, handleOnExit).sendToTarget();
					}
				};
				
				Dialog dialog = CloudDriveDialogUtil.getCloudDriveDialog(this,
						R.string.root_message, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						new Thread(handleExit).start();
					}
				}, null);
				dialog.setCanceledOnTouchOutside(false);
				dialog.setCancelable(false);
				dialog.show();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return true;
		} else {
			return false;
		}
	}
}
